package com.zzh.camera2.permission

import android.annotation.TargetApi
import android.app.Activity
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.widget.Toast

/**
 * @author ：zuhui.zhang
 * time ： 2021/4/29 10:51
 */
class PermissionCheckActivity : Activity() {
    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d(TAG, " onCreate$savedInstanceState")
        if (savedInstanceState == null) {
            val missingArray = intent.getStringArrayExtra(PermissionCheckUtil.MISSING_PERMISSIONS)
            PermissionCheckUtil.setPermissionActivityCount(true)
            if (missingArray != null && missingArray.size > 0 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissionForM(missingArray)
            } else {
                finish()
                returnOriginationActivity()
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.M)
    private fun requestPermissionForM(missingArray: Array<String>) {
        requestPermissions(missingArray, REQUIRED_PERMISSIONS_REQUEST_CODE)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        finish()
        PermissionCheckUtil.setPermissionActivityCount(false)
        Log.d(
            TAG, " onRequestPermissionsResult Activity Count: "
                    + PermissionCheckUtil.sPermissionsActivityStarted
        )
        if (PermissionCheckUtil.onRequestPermissionsResult(
                this, requestCode, permissions, grantResults, true
            )
        ) {
            returnOriginationActivity()
        }
    }

    private fun returnOriginationActivity() {
        try {
            val previousActivityIntent =
                intent.extras!![PermissionCheckUtil.PREVIOUS_ACTIVITY_INTENT] as Intent?
            startActivity(previousActivityIntent)
        } catch (e: SecurityException) {
            Log.e(TAG, " SecurityException happened: $e")
            Toast.makeText(this, "SecurityException happened", Toast.LENGTH_SHORT).show()
        }
    }

    override fun finish() {
        super.finish()
        //关闭窗体动画显示
        overridePendingTransition(0, 0)
    }

    companion object {
        private const val TAG = "PermissionCheckActivity"
        private const val REQUIRED_PERMISSIONS_REQUEST_CODE = 1
    }
}